package com.example.demo.java8.stream;

import com.example.demo.model.Student;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 排序
 *
 * @author Roger
 * @since 2021/7/25
 */
public class SortedTest {

    public static void main(String[] args) {
        // 对Map按照分组销售总值逆序排序
        Map<String, Integer> sortedMap = new LinkedHashMap<>();
        Map<String, Integer> map = new HashMap();
        map.put("1",6);
        map.put("2",9);
        map.put("3",10);
        map.forEach((k, v) -> {
            System.out.println(k + " = " + v);
        });
        map.entrySet().stream().sorted(Map.Entry.<String, Integer> comparingByValue().reversed())
                .forEachOrdered(e -> sortedMap.put(e.getKey(), e.getValue()));

        sortedMap.forEach((k, v) -> {
            System.out.println(k + " = " + v);
        });

        List list = Arrays.asList("1","2","3");
        List list2  = (List) list.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
        list2.stream().forEach(v->{
            System.out.println(v);
        });
        List<Student> sList1 = new ArrayList<>();
        Student s11 = new Student("aa",22);
        Student s12 = new Student("aa",33);
        Student s13 = new Student("xx",44);
        sList1.add(s11);
        sList1.add(s12);
        sList1.add(s13);
        List<Student> list3  = sList1.stream().sorted(Comparator.comparing(Student::getName)).collect(Collectors.toList());
        list3.stream().forEach(v->{
            System.out.println(v.getName());
        });

        List<Student> list4  = sList1.stream().sorted((o1, o2) -> o2.getSex() - o1.getSex()).collect(Collectors.toList());
        list4.stream().forEach(v->{
            System.out.println(v.getSex());
        });

        /*Collections.sort(sList1, new Comparator<Student>() {

            public int compare(Student o1, Student o2) {
                return o2.getSex() - o1.getSex();
            }
        });*/

    }

}
